import { ChartConfigFactory } from '/src/components/component/chart/config/ChartConfigFactory.js'
import { ChartOptionConfig } from '/src/components/component/chart/chartoptionconfig.js'
import * as echarts from 'echarts';
import { ActuatorService } from '/src/api/actuator'
import { Component } from '/src/components/component/component.js';
import { TemplateManager } from '/src/util/templatemanager/templatemanager.js'
import { NotificationManager } from '/src/util/notification/notification.js'
import { TimerManager } from './timermanager.js'

export class ChartComponent extends Component {
    static chartTypeToOptionGenerator = {
        'sequence': 'generateOption',
        'pie': 'generateOptionPie'
    };

    // 使用一个静态 Map 来存储所有实例，替代全局的 chartComponents
    static instances = new Map();

    constructor(container, options) {
        super(container, options);
        this.chart = null;
        this.data = null; // 从接口获取的原始数据
        this.showToolbox = options.showToolbox !== false;
        this.isTitle = options.isTitle !== false;
        this.name = options.name || 'chart';
        this.searchBarComponent = options.searchBarComponent || null;
        this.sourceData = options.sourceData || {};
        this.currentType = options.chartType || 'sequence';
        this.dataSource = options.dataSource;
        
        this.timerManager = new TimerManager(
            () => this.refresh(),
            {
                interval: options.time || 30000,
                name: `${this.name}-timer`
            }
        );

        if (options.time && options.time != 0) {
            console.log(options.time)
            this.startAutoRefresh(options.time);
        }

        this.configInstance = this.createConfigInstance();

        // 创建后立即注册到静态 Map 中
        ChartComponent.instances.set(this.name, this);
    }

    init() {
    }

    async loadData(sourceData) {
        this.sourceData = sourceData;

        try {
            const res = await ActuatorService.doActuator({
                id: sourceData.id,
                title: sourceData.text,
                [sourceData.type]: sourceData.value,
                ...(this.searchBarComponent ? this.searchBarComponent.getSearchData() : {}),
                dataSource: sourceData.dataSource
            });

            this.data = res;
            this.render();
            this.trigger('dataLoaded', res);
        } catch (error) {
            NotificationManager.error('加载图表数据失败:' + error);
            this.showError('数据加载失败', sourceData.text || '图表', 'load-error');
        }
    }

    render() {
        if (!this.data || !this.data.series || !this.data.legend || this.data.legend.length == 0) {
            this.showError('图表数据无效', this.data?.title || '图表', 'invalid-data');
            return;
        }

        const chartDom = this.container[0];
        if (!chartDom) {
            console.error('未找到图表容器:', this.container);
            return;
        }

        if (this.chart) {
            this.chart.off('finished');
            this.chart.dispose();
        }

        this.chart = echarts.init(chartDom);

        const generatorName = ChartComponent.chartTypeToOptionGenerator[this.currentType];
        if (!generatorName || typeof ChartOptionConfig[generatorName] !== 'function') {
            console.error(`不支持的图表类型或生成函数: ${this.currentType}`);
            return;
        }
        const option = ChartOptionConfig[generatorName](this.data, this.showToolbox, this.isTitle);
        this.chart.setOption(option, true);
        this.chart.resize();

        this.chart.on('finished', () => {
            this.trigger('rendered', this.chart);
        });
    }

    createConfigInstance() {
        return ChartConfigFactory.createConfig(this.currentType, this.container, {
            chartType: this.currentType,
            baseConfigContainer: this.$baseConfigContainer,
            seriesConfigContainer: this.$seriesConfigContainer,
            ...this.options
        });
    }

    changeChartType(newType) {
        this.currentType = newType;
        this.configInstance = this.createConfigInstance();

        // 使用公共方法设置配置实例
        this.setupConfigInstance(this.configInstance);
        this.configInstance.generateSeriesConfigForm();
    }

    setupConfigInstance(configInstance) {
        if (!configInstance) return;

        // 设置基本属性
        configInstance.data = this.data;
        configInstance.chart = this.chart;
        configInstance.cid = this.cid;

        // 重新绑定事件
        configInstance.off('configChanged');
        configInstance.off('chartTypeChanged');
        configInstance.on('configChanged', (eventData) => {
            this.render();
            this.trigger('configChanged', eventData);
        });
        configInstance.on('chartTypeChanged', (eventData) => {
            this.changeChartType(eventData.chartType);
            this.render();
            this.trigger('chartTypeChanged', eventData);
        });
    }

    async generateConfigForm() {
        if (!this.configInstance || typeof this.configInstance.generateConfigForm !== 'function') {
            console.warn('配置实例不存在或不支持generateConfigForm方法');
            return;
        }

        // 使用公共方法设置配置实例
        this.setupConfigInstance(this.configInstance);

        // 生成完整的配置表单
        return await this.configInstance.generateConfigForm();
    }

    updateData(newData) {
        this.data = { ...this.data, ...newData };
        this.render();
    }

    resize() {
        if (this.chart) {
            this.chart.resize();
        }
    }

    async showError(reason, title = '图表', status = 'error') {
        const titleSection = this.isTitle ? `
            <div style="
                position: absolute;
                top: 16px;
                left: 16px;
                text-align: left;
                ">
                <span style="
                    color: #666;
                    font-size: 18px;
                    font-weight: 500;
                    ">
                    ${title}
                </span>
            </div>
        ` : '';

        let html = await TemplateManager.loadTemplate('/src/components/component/chart/chart-null-data.html', {
            title: title,
            titleSection: titleSection
        });
        this.container.html(html);
        this.container.attr('data-chart-status', status);
        this.container.attr('data-no-data-reason', reason);
    }

    /**
     * 启动自动刷新
     * @param {number} interval - 刷新间隔（毫秒），可选
     */
    startAutoRefresh(interval) {
        this.timerManager.start(interval);
    }

    /**
     * 停止自动刷新
     */
    stopAutoRefresh() {
        this.timerManager.stop();
    }

    /**
     * 重启自动刷新
     * @param {number} interval - 新的刷新间隔（毫秒），可选
     */
    restartAutoRefresh(interval) {
        this.timerManager.restart(interval);
    }

    /**
     * 设置刷新间隔
     * @param {number} interval - 刷新间隔（毫秒）
     */
    setRefreshInterval(interval) {
        this.timerManager.setInterval(interval);
    }

    async refresh() {
        if (this.sourceData && Object.keys(this.sourceData).length > 0) {
            await this.loadData(this.sourceData);
        }
    }

    /**
     * 销毁组件
     */
    destroy() {
        if (this.timerManager) {
            this.timerManager.destroy();
            this.timerManager = null;
        }

        if (this.chart) {
            this.chart.off();
            this.chart.clear();
            this.chart.dispose();
            this.chart = null;
        }
        // 从静态 Map 中移除
        ChartComponent.instances.delete(this.name);
        super.destroy();
    }

    /**
     * 获取指定名称的 ChartComponent 实例
     * @param {string} name - 实例名称
     * @returns {ChartComponent|null}
     */
    static getInstance(name) {
        return ChartComponent.instances.get(name) || null;
    }

    /**
     * 获取所有 ChartComponent 实例
     * @returns {Map<string, ChartComponent>}
     */
    static getAllInstances() {
        return ChartComponent.instances;
    }

    /**
     * 刷新所有图表（使用缓存数据）
     */
    static refreshAll() {
        ChartComponent.instances.forEach(instance => {
            instance.refresh();
        });
    }

    /**
     * 销毁所有图表实例
     */
    static destroyAll() {
        ChartComponent.instances.forEach(instance => {
            instance.destroy();
        });
        ChartComponent.instances.clear();
    }
}